package com.atguigu.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {
    private Object target;

    public ProxyFactory(CalculatorImpl calculator) {
        target=calculator;
    }

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    public Object getProxy() {
        // 第一个参数：动态生成代理类的代理器
        ClassLoader classLoader = target.getClass().getClassLoader();
        // 第二个参数：目标对象实现的接口的数组
        Class[] interfaces = target.getClass().getInterfaces();
        // 第三个参数：方法
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("动态代理对象日志："+method.getName());
                Object result = method.invoke(target, args);
                System.out.println("结果："+result);
              return result;
            }
        };
        return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
    }
}
